//
//  AuToScrollLabel.m
//  viewTest
//
//  Created by 俞卫忠 on 16/8/16.
//  Copyright © 2016年 YuWeiZhong. All rights reserved.
//

#import "AuToScrollLabel.h"

static CGRect oldFrame;
#define XIB_WIDTH 400

#define S_WIDTH ([[UIScreen mainScreen] bounds].size.width)

static const CGFloat AutoViewDefaultCornerRadius=0.0;

static const CGFloat AutoViewDefaultBorderWidth=0.0;

@implementation AuToScrollLabel

- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self) {
        self.font= [UIFont systemFontOfSize:  S_WIDTH * self.font.pointSize / XIB_WIDTH];
    }
    return self;
}

- (void)prepareForInterfaceBuilder{
    [self drawView];
}

-(void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    [self drawView];
}

/**
 以下项都是添加了一个比例系数，不需要可以直接注释掉代码
 */
-(void)drawView
{
    self.layer.masksToBounds=YES;
    
    CGFloat cornerRadius=self.cornerRadius?self.cornerRadius:AutoViewDefaultCornerRadius;
    
    CGFloat borderWidth=self.borderWidth?self.borderWidth:AutoViewDefaultBorderWidth;
    
    //圆角
    if (cornerRadius>0) {
#if TARGET_INTERFACE_BUILDER
        self.layer.cornerRadius=cornerRadius;
#else
        self.layer.cornerRadius=S_WIDTH*cornerRadius/XIB_WIDTH;
#endif
    }
    
    //边框
    if (borderWidth>0) {
        self.layer.borderWidth=S_WIDTH*borderWidth/XIB_WIDTH;
    }
    
    //边框颜色
    if (self.borderColor) {
        self.layer.borderColor=[self.borderColor CGColor];
    }

    //字幕滚动
    if (self.isScroll) {
        CGSize size = [self.text sizeWithAttributes: @{NSFontAttributeName: self.font}];
        CGRect textRect = self.frame;
        oldFrame = self.frame;
        textRect.size.width = size.width;
        self.frame = textRect;
        if (size.width > oldFrame.size.width) {
            float offset = size.width - oldFrame.size.width + 10 ;
            
            [UIView animateWithDuration:10.0
             
                                  delay:0
             
                                options:UIViewAnimationOptionRepeat //动画重复的主开关
             
             |UIViewAnimationOptionAutoreverse //动画重复自动反向，需要和上面这个一起用
             
             |UIViewAnimationOptionCurveLinear//动画的时间曲线，滚动字幕线性比较合理
                             animations:^{
                                 
                                 self.transform = CGAffineTransformMakeTranslation(-offset, 0);
                                 
                             }
             
                             completion:^(BOOL finished) {
                                 
                             }
             ];
            
        }
    }
}
@end
